package com.example.controller;
import com.example.model.auto.UserInfo;
import com.example.service.IUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author 姚帅
 * @since
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserInfoController {

    @Autowired
    private IUserInfoService iUserInfoService;

    /*查询用户*/
    @GetMapping("/getUser")
    public List<UserInfo> getUser(){
        return iUserInfoService.list();
    }

    /*通过名称查询用户*/
    @GetMapping("/getUserByName/{Name}")
    public int getUserByName(@PathVariable("Name") String Name){
        UserInfo check = iUserInfoService.check(Name);
        if (check!=null){
            Long id = check.getId();
            int a = Math.toIntExact(id);
            return a;
        }else {
            return -1;
        }
    }

    /*通过id查询用户*/
    @GetMapping("/getUserById/{id}")
    public UserInfo getUserById(@PathVariable("id") int id){
        return iUserInfoService.getById(id);
    }

    /*修改用户*/
    @PostMapping("/updateUser")
    public void updateUser(@RequestBody UserInfo user){
        iUserInfoService.updateById(user);
    }

    /*添加用户*/
    @PostMapping("/setUser")
    public void setUser(@RequestBody UserInfo user){
        user.setGmtCreate(new Date());
        iUserInfoService.save(user);
    }

    /*删除用户*/
    @PostMapping("/deletedById/{id}")
    public boolean deleted(@PathVariable("id") int id){
        return iUserInfoService.removeById(id);
    }

    /*用户登录*/
    @PostMapping("/login")
    public int Login(@RequestBody UserInfo user){
        System.out.println(user.getIdCard());
        System.out.println(user.getPassword());
        UserInfo login = iUserInfoService.login(user.getIdCard(), user.getPassword());
        if (login!=null){
            Long id = login.getId();
            int a = Math.toIntExact(id);
            System.out.println(a);
            return a;
        }else {
            return -1;
        }
    }

    /*图片上传*/
    @PostMapping("/elupload")
    public String elUpload(MultipartFile file){
        String fileName = file.getOriginalFilename();
        System.out.println("进来了");
        File dest = new File("D:\\monkey\\data\\csdn\\vue\\csdn-Web\\static\\img\\" + fileName);
        try {
            file.transferTo(dest);
            return "上传成功";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败！";
    }

}
